package com.zjh.admin.app.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.app.model.AppUserEntity;
import com.zjh.admin.app.service.AppUserService;
import com.zjh.admin.sys.model.ResourceEntity;
import com.zjh.admin.sys.model.UserEntity;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.dtgrid.util.ExportUtils;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.common.util.TreeUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import com.zjh.core.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

/**
 * @Author WYX
 * @Description appUSer controller
 * @Date 2019/11/17 18:00
 */
@Controller
@RequestMapping("/appUser/")
public class AppUserController extends BaseController {

    @Autowired
    private AppUserService appUserService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/app/user/list";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * ajax分页查询app用户信息
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "list.html")
    @ResponseBody
    public Object list(String gridPager, HttpServletResponse response) throws Exception {
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        Map<String, Object> parameters = pager.getParameters();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));
        //3、判断是否是导出操作
        if (pager.getIsExport()) {
            if (pager.getExportAllData()) {
                //3.1、导出全部数据
                List<AppUserEntity> list = appUserService.queryListByPage(parameters);
                ExportUtils.exportAll(response, pager, list);
                return null;
            } else {
                //3.2、导出当前页数据
                ExportUtils.export(response, pager);
                return null;
            }
        } else {
            //设置分页，page里面包含了分页信息
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
            List<AppUserEntity> list = appUserService.queryListByPage(parameters);
            parameters.clear();
            setPageList(parameters, pager, page, list);
            return parameters;
        }
    }

    /**
     * add跳转
     *
     * @return
     */
    @RequestMapping("addUI.html")
    public String addUI() {
        return Common.BACKGROUND_PATH + "/app/user/form";
    }

    /**
     * 用户注册
     *
     * @param appUserEntity
     * @return
     */
    @RequestMapping("add.html")
    @ResponseBody
    public Object add(AppUserEntity appUserEntity) {
        Result<AppUserEntity> result = new Result();
        try {
            int status = appUserService.insert(appUserEntity);
            if (status > 0) {
                result.setData(appUserEntity);
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     *
     * @param appUserEntity
     * @return
     */
    @RequestMapping("login.html")
    @ResponseBody
    public Object login(AppUserEntity appUserEntity) {
        Result<Map> result = new Result<>();
        Map<String, Object> resultData = new HashMap<>();
        AppUserEntity appUser = appUserService.findByAccountName(appUserEntity);
        if (appUser == null) {
            resultData.put("error", "账号不存在");
            resultData.put("accountName", appUserEntity.getuAccountName());
            resultData.put("password", appUserEntity.getuPassword());
            result.error("账号不存在");
        } else if (!StringUtils.equals(appUser.getuPassword(), appUserEntity.getuPassword())) {
            resultData.put("error", "账号或密码错误");
            resultData.put("accountName", appUserEntity.getuAccountName());
            resultData.put("password", appUserEntity.getuPassword());
            result.error("账号或密码错误");
        } else if (appUser.getuLocked() == 1) {
            resultData.put("error", "账号被锁定");
            resultData.put("accountName", appUserEntity.getuAccountName());
            resultData.put("password", appUserEntity.getuPassword());
            result.error("账号被锁定");
        } else {
            result.success("登录成功");
            resultData.put("appUserEntity",appUser);
        }
        result.setData(resultData);
        return result;
    }

    /**
     * edit跳转
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("editUI.html")
    public String editUI(Model model, HttpServletRequest request, Long id) {
        try {
            AppUserEntity appUserEntity = appUserService.findById(id);
            PageUtil page = new PageUtil();
            setPage(request, page);

            model.addAttribute("page", page);
            model.addAttribute("appUserEntity", appUserEntity);
            return Common.BACKGROUND_PATH + "/app/user/form";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 修改用户资料
     *
     * @param appUserEntity
     * @return
     */
    @RequestMapping("edit.html")
    @ResponseBody
    public Object update(AppUserEntity appUserEntity) {
        Result result = new Result();
        try {
            int status = appUserService.update(appUserEntity);
            if (status > 0) {
                result.success("编辑成功");
            } else {
                result.error("编辑失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 锁定账户
     *
     * @param id
     * @return
     */
    @RequestMapping("lock.html")
    @ResponseBody
    public Object updateLockStatus(String id) {
        Result result = new Result();
        try {
            int status = appUserService.updateLockStatus(Long.valueOf(id));
            if (status > 0) {
                result.success("编辑成功");
            } else {
                result.error("编辑失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 验证角色名称是否存在相同
     *
     * @param appUserEntity
     * @return
     */
    @RequestMapping("withoutAuth/validateAccountName.html")
    @ResponseBody
    public Object validateRoleName(AppUserEntity appUserEntity) {
        try {
            System.out.println(appUserEntity.getuAccountName());
//            roleName = new String(roleName.getBytes("iso-8859-1"), "utf-8");
            AppUserEntity appUser = appUserService.findByAccountName(appUserEntity);
            return appUser == null;
        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * 图片上传
     *
     * @param multipartFile
     * @param request
     * @return 上传结果
     */
    @RequestMapping("imageUpload")
    @ResponseBody
    public Result upload(MultipartFile multipartFile, HttpServletRequest request) {
        Result<Map> result = new Result<>();
        String iconPath;
        try {
            if (multipartFile != null && !multipartFile.isEmpty()) {
                //获取file的名
                String fileName = multipartFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                if (!".jpg".equalsIgnoreCase(suffix) && !".png".equalsIgnoreCase(suffix)) {
                    result.error("格式错误,支持图片的格式: jpg, png");
                } else {
                    String fileRealPath = request.getSession().getServletContext().getRealPath("/") + Common.UPLOAD_IMAGE_PATH + "/appUser/";
                    //自定义图片上传位置,这里是上传到项目的upload下，需要手动刷新下upload文件夹页面才能显示，如果存放在服务器的话
                    //每次重启服务器图片都会消失
                    String webPath = Common.UPLOAD_IMAGE_PATH + "/appUser/";

                    String tempName = UUID.randomUUID().toString();

                    //判断文件夹是否存在
                    File targerFile = new File(fileRealPath);
                    if (!targerFile.exists()) {
                        targerFile.mkdirs();
                    }
                    //保存文件
                    File uploadFile = new File(fileRealPath + tempName + suffix);
                    FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);
                    iconPath = webPath + tempName + suffix;
                    Map<String, Object> data = new HashMap<>();
                    data.put("imageUrl", iconPath);
                    result.setData(data);
                    result.success("上传成功");
                }
            }
        } catch (Exception e) {
            result.error("文件上传失败");
        }
        return result;
    }

}
